package com.insigma.business.qrcode.soldier.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.insigma.business.qrcode.common.util.RedisUtils;
import com.insigma.business.qrcode.soldier.dto.CodeEngineResponse;
import com.insigma.business.qrcode.soldier.dto.CodeEngineSoldierBasicInfo;
import com.insigma.business.qrcode.soldier.service.CodeEngineService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;


@Slf4j
@Service("codeEngineServiceRedis")
public class CodeEngineServiceRedisImpl implements CodeEngineService {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public CodeEngineResponse queryQrString(CodeEngineSoldierBasicInfo basicInfo) {
        log.info("通过redis获取code");
        String idCardNo = basicInfo.getIdCardNo();
        String yyyyMMddHH = DateUtil.formatDate(new Date(), "yyyyMMddHH");
        //生成老兵码
        String code = "25" + yyyyMMddHH + UUID.randomUUID().toString();
        Object o = redisUtils.get(code);
        if (o == null) {
            CodeEngineResponse result = new CodeEngineResponse();
            result.setSuccess(true);
            CodeEngineSoldierBasicInfo codeEngineSoldierBasicInfo = new CodeEngineSoldierBasicInfo();
            codeEngineSoldierBasicInfo.setLevel("green");
            codeEngineSoldierBasicInfo.setIdCardNo(idCardNo);
            codeEngineSoldierBasicInfo.setRealName(basicInfo.getRealName());
            codeEngineSoldierBasicInfo.setCode(code);
            result.setData(codeEngineSoldierBasicInfo);

            o = JSON.toJSONString(result);
            redisUtils.set(code, o, 1800);
        }

        String str = (String) o;
        CodeEngineResponse codeEngineResponse = JSONObject.parseObject(str, CodeEngineResponse.class);
        return codeEngineResponse;
    }

    @Override
    public CodeEngineResponse queryBasicInfoByCode(String qrString) {
        Object o = redisUtils.get(qrString);
        if (o == null) {
            return null;
        }
        CodeEngineResponse codeEngineResponse = JSONObject.parseObject((String) o, CodeEngineResponse.class);
        return codeEngineResponse;
    }

}
